<script setup>
import {onBeforeMount, onMounted, onUpdated, reactive, ref ,onActivated,watch} from "vue";

const emit = defineEmits(['remoteMethod', 'validatorRules', 'selectChangeFun', 'updateOptions'])
const props = defineProps({
  tableColumn: { type: Array },
  formData: { type: Object },
  isRead: false
})
const formLabelWidth = ref(150)
const formRules = ref({})
const buildFormRules = () => {
  let _formRules = {};
  if(props.isRead){
    formRules.value = _formRules;
    return false;
  }
  for (const column of props.tableColumn.filter(item=>item.isForm)) {
    const rules = [];
    if (column.required) {
      rules.push({
        required: column.required,
        message: `请输入${column.label}`,
        trigger: ["select", "select_remote"].includes(column.formType) ? "change" : "blur"
      })
    }
    if (column.formType === "input" && column.max > 0) {
      rules.push({
        min: column.min || 0,
        max: column.max || 0,
        message: `${column.label}长度不能大于${column.max}`,
        trigger: 'blur'
      })
    }
    if (column.validatorRules) {
      rules.push({
        validator: (rule, value, callback) => emit('validatorRules', column.prop, rule, value, callback)
      })
    }

    if (column.isAdd) {
      _formRules[column.prop] = (index, indexProcesses) => rules;
    } else {
      _formRules[column.prop] = rules;
    }
  }
  formRules.value = _formRules;
}

const buildFormSelData = async () => {
  for (const key in props.formData) {
    props.formData[key] === 0 ? delete props.formData[key] : null
  }
}

let isThrottling = ref(false);
const timer = ref(null);
const selectChangeFun = (value, f) => {
  if (f.isChangeFun) {
    emit("selectChangeFun", value, f)
  }
}
const remoteMethod = async (query, f) => {
  if (query === "") {
    return
  }
  // 如果已经在节流控制中，则直接返回，不执行后续操作
  if (isThrottling.value) return;

  // 设置节流控制标志，防止在等待期间再次触发
  isThrottling.value = true;

  await emit("remoteMethod", query, f)

  // 设置节流时间，之后重置标志允许再次执行
  clearTimeout(timer.value); // 确保只有最后一次设置的定时器被执行
  timer.value = setTimeout(() => {
    isThrottling.value = false;
  }, 500); // 设置和防抖相同的时间间隔，或根据需要调
}
const addOptions = (f) => {
  emit("updateOptions", f)
}
const deleteOptions = (f, index) => {
  emit("updateOptions", f, index)
}

const ruleFormRef = ref()
const resetFields = () => {
  ruleFormRef.value.resetFields();
}
onBeforeMount(()=>{
  buildFormRules();
})
onMounted(async() => {
  await buildFormSelData();
  setTimeout(()=>{

    ruleFormRef.value.clearValidate();
  }, 1000)
})

watch(() => props.isRead, (newValue, oldValue) => {
  // 这里处理isRead变化后的逻辑
  console.log(`isRead变化了，新值为：${newValue}, 旧值为：${oldValue}`);
  buildFormRules()
});

defineExpose({
  resetFields,
  buildFormSelData,
  ruleFormRef
})
</script>

<template>
  <el-form :model="formData" :rules="formRules" ref="ruleFormRef">
    <div v-for="(f, fk) in tableColumn.filter(item=>item.isForm)" :key="fk">
      <div class="form-item" v-if="!f.isAdd" >
        <el-form-item :label="f.label + ':'" :label-width="formLabelWidth" :prop="f.prop">
          <!-- 查看 -->
          <div v-if="isRead">
            <span v-if="f.formType === 'radio'">{{f.enum[formData[f.prop]]}}</span>
            <span v-else-if="f.formType === 'select'">
            {{ f.asyncSelData.find(i=>i.id === formData[f.prop])?.name
            || f.asyncSelData.find(i=>i.id === formData[f.prop])?.value }}
          </span>
            <span v-else>{{formData[f.prop]}}</span>
          </div>
          <!-- children start -->
          <div class="childrenForm" v-else-if="!isRead && f.formType === 'custom'" >
            <el-form-item v-for="(c, ck) in f.children" :key="ck" :prop="c.prop">
              <el-input v-if="c.formType === 'input'" v-model="formData[c.prop]" :placeholder="`请输入${c.label}`" :type="c.inputType" autocomplete="off" :maxlength="c.max || -1" :minlength="c.min || 0" show-word-limit />
              <el-input-number v-else-if="c.formType === 'number'" v-model="formData[c.prop]" :placeholder="`请输入${c.label}`" controls-position="right" :min="c.min" :max="c.max"></el-input-number>
              <el-select v-else-if="c.formType === 'select'"
                         v-model="formData[c.prop]" filterable
                         :multiple="c.multiple || false"
                         :clearable="true"
                         :placeholder="`请选择${c.label}`">
                <el-option v-for="(sel, selKey) in c.asyncSelData" :key="selKey" :value="sel.id" :label="sel.name || sel.value"></el-option>
              </el-select>
              <el-checkbox
                v-else-if="c.formType === 'checkbox'" v-model="c.prop">{{ c.label }}</el-checkbox>
            </el-form-item>
          </div>
          <!-- children end -->
          <el-input  v-else-if="!isRead && f.formType === 'input'" v-model="formData[f.prop]" :placeholder="`请输入${f.label}`" :type="f.inputType" autocomplete="off" :maxlength="f.max || -1" :minlength="f.min || 0" show-word-limit />
          <el-input-number v-else-if="!isRead && f.formType === 'number'" v-model="formData[f.prop]" :placeholder="`请输入${f.label}`" controls-position="right" :min="f.min" :max="f.max"></el-input-number>
          <el-input v-else-if="!isRead && f.formType === 'textarea'" v-model="formData[f.prop]" :placeholder="`请输入${f.label}`" type="textarea" autocomplete="off" :maxlength="f.max || -1" :minlength="f.min || 0" show-word-limit />
          <el-radio-group v-else-if="!isRead && f.formType === 'radio'" v-model="formData[f.prop]">
            <el-radio v-for="(sel, selKey) in Object.keys(f.enum).filter(i=>i>0)" :key="selKey" :value="Number(sel)">{{ f.enum[sel] }}</el-radio>
          </el-radio-group>

          <el-select v-else-if="!isRead && f.formType === 'select'"
                     v-model="formData[f.prop]" filterable
                     :multiple="f.multiple"
                     :clearable="true"
                     @change="value => selectChangeFun(value, f)"
                     :placeholder="`请选择${f.label}`">
            <el-option v-for="(sel, selKey) in f.asyncSelData" :key="selKey" :value="sel.id" :label="sel.name || sel.value"></el-option>
          </el-select>

          <el-select v-else-if="!isRead && f.formType === 'select_remote'"
                     v-model="formData[f.prop]" filterable remote
                     :remote-method="(query) => remoteMethod(query, f)"
                     :multiple="f.multiple"
                     :placeholder="`请选择${f.label}`">
            <el-option v-for="(sel, selKey) in f.asyncSelData" :key="selKey" :value="sel.id" :label="sel.name || sel.value"></el-option>
          </el-select>

          <el-switch v-else-if="!isRead && f.formType === 'switch'" v-model="formData[f.prop]"> </el-switch>

          <el-upload v-else-if="!isRead && f.formType === 'image'" class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
                     :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="formData[f.prop]" :src="formData[f.prop]" alt="" class="avatar">
            <div class="upLoadImg">
              <img class="addImg" src="/src/assets/addIm g.png" alt="">
              <div class="title">上传图片</div>
            </div>
          </el-upload>
        </el-form-item>
        <div class="tips">{{ f.tips }}</div>
      </div>
      <el-form-item v-else v-for="(fcItem, fcIndex) in formData[f.prop]" :key="fcIndex" :label="f.label + (fcIndex + 1) + ':'" :label-width="formLabelWidth" :prop="f.prop + '[' + fcIndex + '].title'" :rules="!isRead ? formRules[f.prop](fcIndex) : null">
        <span v-if="isRead">{{fcItem['title']}}</span>
        <div class="form-item" v-else>
          <img src="/src/assets/delete.png" class="formClose" style="width: 20px; height: 20px; margin-right: 10px; cursor: pointer;" @click="deleteOptions(f, fcIndex)" v-if="fcIndex>0"  alt=""/>
          <el-input v-model="formData[f.prop][fcIndex]['title']" :placeholder="`请输入${f.label}${fcIndex + 1}`" :type="f.inputType" autocomplete="off" :maxlength="f.max || -1" :minlength="f.min || 0" show-word-limit />
        </div>
      </el-form-item>

      <el-button v-if="!isRead && f.isAdd" link type="primary" :style="'margin-left: '+(formLabelWidth)+'px'" @click="addOptions(f)">添加选项</el-button>
    </div>
  </el-form>
</template>

<style scoped lang="scss">
.form-item {
  display: flex;
  align-items: center;
  width: 100%;
  >div:first-of-type {
    width: 100%;
  }
  .tips {
    flex: none;
    padding-left: 10px;
    color: rgb(192, 196, 204);
  }
}
  ::v-deep .el-input__inner::-webkit-input-placeholder {
    color: #b6bcc4;
    font-size: 12px;
  }

  ::v-deep .el-textarea__inner::-webkit-input-placeholder {
    color: #b6bcc4;
    font-size: 12px;
  }

  ::v-deep .el-form-item__label {
    font-weight: 500;
    color: #515a6e;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  //上传的样式
  .upLoadImg {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    padding: 10px 15px;
    text-align: center;
    width: 120px;

    .title {
      font-size: 12px;
      color: #8c939d;
    }

    .addImg {
      width: 40px;
      height: 40px;
    }
  }

  .childrenForm {
    display: flex;
    width: 100%;
    .el-input-number {
      width: 100%;
    }
    .el-form-item {
      width: 100%;
      margin-right: 10px;
      &:last-of-type {
        margin-right: 0;
      }
    }
    .el-select {
      width: 100%;
    }
  }
</style>
